<template>
  <div>
    <!-- 头部标题 -->
    <van-nav-bar title="登录" left-arrow @click-left="onBack" />

    <!-- 主体 -->
    <van-form :scroll-to-error="true" @submit="hLogin">
      <van-field
        v-model.trim="userInfo.mobile"
        name="mobile"
        label="手机号"
        type="tel"
        placeholder="请输入手机号"
        :rules="[{ required: true, message: '请填写正确手机号' ,pattern :/^\d{11}$/}]"
      />
      <van-field
        v-model.trim="userInfo.code"
        type="password"
        name="code"
        label="验证码"
        placeholder="请输入验证码"
        :rules="[{ required: true, message: '请填写正确验证码',pattern :/^\d{6}$/ }]"
      />
      <div style="margin: 16px">
        <van-button round block type="info" sizi="mini" native-type="submit">
          登录
        </van-button>
      </div>
    </van-form>
  </div>
</template>
<style lang="less" scoped>
.van-button {
  height: 32px;
  line-height: 30px;
}
</style>
<script>
import { login, getProfile } from '@/api/user.js'
export default {
  name: 'Login',
  data () {
    return {
      userInfo: {
        mobile: '13912345678',
        code: '246810'
      }
    }
  },
  methods: {
    onBack () { // 返回主页
      this.$router.push('/')
    },
    async  hLogin (userInfo) { // 登录
      this.$toast.loading({ // 登录中
        duration: 0, // 持续展示 toast,永远不会关闭
        overlay: true, // 整体添加一个遮罩
        message: '登录中...'
      })
      try {
        // 1.获取token
        const tokenInfo = await login(userInfo)
        // 2.存入vuex
        this.$store.commit('mSetTokenInfo', tokenInfo.data)
        // 3.获取用户信息
        const profile = await getProfile()
        // 4.存入vuex
        this.$store.commit('mUserInfo', profile.data)
        // 5.弹出成功提示框
        this.$toast.success('登陆成功')
        // 6. 跳转到目标页
        const url = this.$route.query.backto || '/'
        this.$router.push(url)
      } catch (err) {
        console.log(err, '登录失败')
        this.$toast.fail('登陆失败')
      }
    }
  }
}
</script>
